package com.mnt.washio.activities;

import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;

import java.util.ArrayList;
import java.util.Date;

import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mnt.washio.R;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;
import com.mnt.washio.utils.network.ws.AddCreditCardWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl.WebServiceFlag;
import com.mnt.washio.views.CongraDialog;
import com.mnt.washio.views.CustomDialog;
import com.parse.ParseUser;
import com.stripe.android.Stripe;
import com.stripe.android.TokenCallback;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;

public class RegisterStep3Activity extends BaseActivityNoTitle implements
		OnClickListener, WebServiceCommunicatorListener {
	private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int

	private TextView myEdtExpirration1;
	private TextView myEdtExpirration2;
	private TextView mTvSkip;
	private EditText mEdtCardNumber, mEdtCVC;
	private CustomDialog myDialogMonth, myDialogYearh;
	private int myPositionMonth = 0, myPositionYear = 0;
	private Button myBtnAddCard, myBtnScan;
	private TextView myTvTitle;
	private ArrayList<Object> arrYear;
	private ArrayList<Object> arrMonth;
	private boolean isRegisterStep = false;
	private ProgressDialog mLoadingDialog;

	@Override
	public int getContentView() {
		return R.layout.fragment_register_step_3;
	}

	@Override
	public void initProperties() {
		isRegisterStep = getIntent().getBooleanExtra("REGISTER", false);

		if (!isRegisterStep) {
			myTvTitle.setVisibility(View.INVISIBLE);
			mTvSkip.setVisibility(View.INVISIBLE);
		}
		arrMonth = new ArrayList<Object>();
		final String[] array = getResources().getStringArray(R.array.arr_month);
		for (int i = 0; i < array.length; i++) {
			arrMonth.add(array[i]);
		}

		arrYear = new ArrayList<Object>();
		@SuppressWarnings("deprecation")
		int year = new Date().getYear() + 1900;
		for (int i = year; i < year + 18; i++) {
			arrYear.add(i);
		}
	}

	@Override
	public void initViews() {
		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setMessage("Loading...");
		mLoadingDialog.setCancelable(false);

		overridePendingTransition(R.anim.slide_in_from_right, R.anim.anim_alpha);
		myEdtExpirration1 = (TextView) findViewById(R.id.edt_expirration_1);
		myEdtExpirration2 = (TextView) findViewById(R.id.edt_expirration_2);

		mEdtCardNumber = (EditText) findViewById(R.id.edt_card_number);
		mEdtCVC = (EditText) findViewById(R.id.edt_cvc);

		myBtnAddCard = (Button) findViewById(R.id.btn_add_card);
		myBtnScan = (Button) findViewById(R.id.btn_scan);
		myTvTitle = (TextView) findViewById(R.id.tv_title_step3);
		myEdtExpirration1.setText((getResources()
				.getStringArray(R.array.arr_month))[0] + "");
		myEdtExpirration2.setText("2014");
		myEdtExpirration1.setFocusableInTouchMode(false);

		mTvSkip = (TextView) findViewById(R.id.tv_skip);
	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
		myEdtExpirration1.setOnClickListener(this);
		myEdtExpirration2.setOnClickListener(this);
		myBtnAddCard.setOnClickListener(this);
		myBtnScan.setOnClickListener(this);
		mTvSkip.setOnClickListener(this);
	}

	public void showDialogMonth() {

		myDialogMonth = new CustomDialog(this, arrMonth, getResources()
				.getString(R.string.txt_expiration_month), myPositionMonth);
		myDialogMonth.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				position -= 1;
				myEdtExpirration1.setText(arrMonth.get(position) + "");
				myPositionMonth = position;
			}
		});
		myDialogMonth.show();
	}

	public void showDialogYear() {

		myDialogYearh = new CustomDialog(this, arrYear, getResources()
				.getString(R.string.txt_expiration_year), myPositionYear);
		myDialogYearh.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				position -= 1;
				myEdtExpirration2.setText(arrYear.get(position) + "");
				myPositionYear = position;
			}
		});
		myDialogYearh.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edt_expirration_1:
			showDialogMonth();
			break;
		case R.id.edt_expirration_2:
			showDialogYear();
			break;
		case R.id.btn_add_card:
			validateAndSave();
			break;
		case R.id.btn_scan:
			onStartScaner();
			break;
		case R.id.tv_skip:
			finish();
			break;
		}
	}

	private void onStartScaner() {
		if (!CardIOActivity.canReadCardWithCamera(this)) {
			Statics.showToast(this, "This feature is not supported");
			return;
		}

		// This method is set up as an onClick handler in the layout xml
		// e.g. android:onClick="onScanPress"

		Intent scanIntent = new Intent(this, CardIOActivity.class);

		// required for authentication with card.io
		scanIntent
				.putExtra(CardIOActivity.EXTRA_APP_TOKEN, Statics.MY_CARDIO_APP_TOKEN);

		// customize these values to suit your needs.
		scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default:
																		// true
		scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default:
																		// false
		scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default:
																				// false

		// hides the manual entry button
		// if set, developers should provide their own manual entry mechanism in
		// the app
		scanIntent.putExtra(CardIOActivity.EXTRA_SUPPRESS_MANUAL_ENTRY, true); // default:
																				// false

		// MY_SCAN_REQUEST_CODE is arbitrary and is only used within this
		// activity.
		startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
			CreditCard scanResult = data
					.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);

			mEdtCardNumber.setText(scanResult.getRedactedCardNumber());

			// Do something with the raw number, e.g.:
			// myService.setCardNumber( scanResult.cardNumber );

			if (scanResult.isExpiryValid()) {
				

				myEdtExpirration1.setText(arrMonth
						.get(scanResult.expiryMonth - 1) + "");
				myPositionMonth = scanResult.expiryMonth - 1;

				myEdtExpirration2.setText(scanResult.expiryYear + "");
				myPositionYear = arrYear.indexOf(scanResult.expiryYear);

			}

			if (scanResult.cvv != null) {
				mEdtCVC.setText(scanResult.cvv);
			}
		} else {
			Statics.showToast(this, "Scan was canceled.");
		}

		

	}

	private void validateAndSave() {
		// if (mEdtCVC.getText().toString().trim().length() == 0) {
		// Statics.showToast(this, "Please input CVC number");
		// return;
		// }

		Card card = new Card(mEdtCardNumber.getText().toString().trim(),
				myPositionMonth + 1, Integer.parseInt(arrYear
						.get(myPositionYear) + ""), mEdtCVC.getText()
						.toString().trim());
		boolean validation = card.validateCard();
		if (validation) {
			mLoadingDialog.show();
			new Stripe().createToken(card, Statics.PUBLISHABLE_KEY,
					new TokenCallback() {
						public void onSuccess(Token token) {
							new AddCreditCardWSControl(
									RegisterStep3Activity.this,
									RegisterStep3Activity.this, ParseUser
											.getCurrentUser().getObjectId(),
									ParseUser.getCurrentUser().getString(
											"stripeId"), token.getId())
									.execute();
						}

						public void onError(Exception error) {
							mLoadingDialog.dismiss();
							Statics.showToast(
									getBaseContext(),
									"Validate card was fail: "
											+ error.getMessage());
						}
					});
		} else {
			Statics.showToast(getBaseContext(),
					"You did not enter a valid card");
		}
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		mLoadingDialog.show();
	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		mLoadingDialog.dismiss();
		Statics.showToast(getBaseContext(), error);
	}

	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		mLoadingDialog.dismiss();
		if (flag == WebServiceFlag.ADD_CARD) {
			if (result != null) {
				com.mnt.washio.objects.Card card = (com.mnt.washio.objects.Card) result;
				Intent intent = new Intent();
				intent.putExtra("card", card);
				setResult(RESULT_OK, intent);
				
				Statics.showToast(this, "Successful");
				finish();
			}
		}
	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
	}

}
